<?php

namespace app\company\model;


use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use app\mini\model\Store;

/**
 * @property int $id
 * @property string $no 编号
 * @property string $name 名称
 * @property string $remark 备注
 * @property int $status 状态
 * @property int $company_id 公司id
 * @property int $deliver_driver_id 司机ID
 * @property int $warehouse_id 车辆ID
 */
class DeliverLine extends Base
{

    public static function onBeforeInsert(DeliverLine $model): void
    {
        $model->company_id = getCompanyId();
    }

    /**
     * @param DeliverLine $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     *
     */
    public static function onAfterInsert(DeliverLine $model): void
    {
        //LX+6位数自增长
        $model->no = "LX" . str_pad($model->id, 6, '0', STR_PAD_LEFT);
        $model->save();

        if ($stores = request()->param('store_ids', '')) {
            $storeModel = Store::whereIn('id', $stores)->where('deliver_line_id', 0)->select();
            if ($storeModel->isEmpty()) exception('门店有误');
            $storeModel->update(['deliver_line_id' => $model->id]);
        }
    }


    /**
     * @param DeliverLine $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     *
     */
    public static function onBeforeDelete(DeliverLine $model): void
    {
        if ($model->stores()->count() > 0){
            Store::where('deliver_line_id', $model->id)->update(['deliver_line_id' => 0]);
        }
    }

}